# plot_excel.py
import csv
import getopt
import sys
import math
import time
import numpy as np
import matplotlib.pyplot as plt
import numba as numba

azi_range = 180
ele_range = 45
tagPoloar_range = 180
filename = 'calib_V317_1009C_H.npy'


@numba.vectorize([numba.float64(numba.complex128), numba.float32(numba.complex64)])
def abs2(x):
    return (x.real**2+x.imag**2)


class SignalProcessor:
    def __init__(self, filename) -> None:
        calib = np.load(file=filename)
        self.cal_v = calib[:, :, 0, :]
        self.cal_h = calib[:, :, 1, :]

    def plot_diff(self, vec):
        azi_range = int(180)
        ele_range = int(45)
        arr_v = np.tensordot(self.cal_v, vec, axes=([2], [0]))
        arr_h = np.tensordot(self.cal_h, vec, axes=([2], [0]))
        arr = abs2(arr_v)+abs2(arr_h)

        azi = (arr.argmax()//ele_range)*2  # 0=360
        ele = (arr.argmax() % ele_range)*2  # 0-90
        # arr_v = abs2(arr_v)   # array v
        # arr_h = abs2(arr_h) # array h
        return arr_v, arr_h, azi, ele


def allExcel():
    pol = 2  # 水平
    chn = 12  # 通道
    calibo3 = np.zeros((tagPoloar_range, pol, chn), dtype=np.complex64)
    vec_a3 = np.zeros(12, dtype=np.complex64)

    s_filename = '2021_10-25_OTA_Polar_V317' + '\Polar_ele70.txt'
    with open(s_filename) as f:
        f_csv = csv.reader(f)
        i = 0
        for row in f_csv:
            theta = 0  # 0-90
            phi = 0  # 0-360
            tag_pol = int(int(row[1])/2)
            pol_HV = row[4]
            if pol_HV == 'V':
                pol = 0
            else:
                pol = 1
            ichn = int(row[5])
            if ichn != 0:
                data3_r = float(row[10])
                data3_i = float(row[11])
                vec3 = complex(data3_r, data3_i * (-1))
                calibo3[tag_pol, pol, ichn - 1] = vec3
    sp = SignalProcessor(filename)
    with open('calib_V317_ele70_2478MHzALL.csv', 'a') as fp:
        fp.write('Ant_polar,' + 'tag_polar,' +
                 'horizontal_value,'+'horizontal_degree,'+'real,'+'imag,'+'vertical_value,'+'vertical_degree,'+'real,'+'imag,'+'sum_vh' + '\n')
        for p in range(180):
            for z in range(2):
                for i in range(12):
                    vec_a3[i] = calibo3[p, z, i]
                
                norm3 = np.linalg.norm(vec_a3)
                vec_a3 = vec_a3 / norm3
                arr_v, arr_h, m_azi, m_ele = sp.plot_diff(vec_a3)
                if z == 0:
                    pol = 'V'
                else:
                    pol = 'H'
                for azi in range(azi_range):
                    for ele in range(ele_range):

                        degree_h = np.degrees(np.angle(arr_h[azi, ele]))
                        if degree_h < 0:
                            degree_h = degree_h % 360
                        value_h = np.abs(arr_h[azi, ele])
                        real_h = np.real(arr_h[azi, ele])
                        imag_h = np.imag(arr_h[azi, ele])
                        degree_v = np.degrees(np.angle(arr_v[azi, ele]))
                        if degree_v < 0:
                            degree_v = degree_v % 360

                        value_v = np.abs(arr_v[azi, ele])
                        real_v = np.real(arr_v[azi, ele])
                        imag_v = np.imag(arr_v[azi, ele])
                        sum_vh = value_h**2+value_v**2

                        result = '{},{},{},{},{},{},{},{},{},{},{}\n'.format(
                            pol, 2*p, value_h, degree_h, real_h, imag_h, value_v, degree_v, real_v, imag_v, sum_vh)
                        fp.write(result)


def screen(az, el):
    az = int(az)
    el = int(el)

    pol = 2  # 水平
    chn = 12  # 通道
    calibo3 = np.zeros((tagPoloar_range, pol, chn), dtype=np.complex64)
    vec_a3 = np.zeros(12, dtype=np.complex64)

    s_filename = '2021_10-25_OTA_Polar_V317' + '\Polar_ele70.txt'
    with open(s_filename) as f:
        f_csv = csv.reader(f)
        i = 0
        for row in f_csv:
            theta = 0  # 0-90
            phi = 0  # 0-360
            tag_pol = int(int(row[1])/2)
            pol_HV = row[4]
            if pol_HV == 'V':
                pol = 0
            else:
                pol = 1
            ichn = int(row[5])
            if ichn != 0:
                data3_r = float(row[10])
                data3_i = float(row[11])
                vec3 = complex(data3_r, data3_i * (-1))
                calibo3[tag_pol, pol, ichn - 1] = vec3
    sp = SignalProcessor(filename)
    with open('calib_V317_ele70_2478MHz[{},{}].csv'.format(az, el), 'a') as fp:
        fp.write('Ant_polar,' + 'tag_polar,' +
                 'horizontal_value,'+'horizontal_degree,'+'real,'+'imag,'+'vertical_value,'+'vertical_degree,'+'real,'+'imag,'+'sum_vh' + '\n')
        for p in range(180):
            for z in range(2):
                for i in range(12):
                    vec_a3[i] = calibo3[p, z, i]
                norm3 = np.linalg.norm(vec_a3)
                vec_a3 = vec_a3 / norm3
                arr_v, arr_h, m_azi, m_ele = sp.plot_diff(vec_a3)
                if z == 0:
                    pol = 'V'
                else:
                    pol = 'H'
                # for azi in range(1):
                    # for ele in range(35):

                degree_h = np.degrees(np.angle(arr_h[az, el]))
                if degree_h < 0:
                    degree_h = degree_h % 360
                value_h = np.abs(arr_h[az, el])
                real_h = np.real(arr_h[az, el])
                imag_h = np.imag(arr_h[az, el])
                degree_v = np.degrees(np.angle(arr_v[az, el]))
                if degree_v < 0:
                    degree_v = degree_v % 360

                value_v = np.abs(arr_v[az, el])
                real_v = np.real(arr_v[az, el])
                imag_v = np.imag(arr_v[az, el])
                sum_vh = value_h**2+value_v**2

                result = '{},{},{},{},{},{},{},{},{},{},{}\n'.format(
                    pol, 2*p, value_h, degree_h, real_h, imag_h, value_v, degree_v, real_v, imag_v, sum_vh)
                fp.write(result)


def help():
    print('-h help')
    print('python ploy_excel.py\t\tsee all data')
    print('python ploy_excel.py -l 0,35\tOnly see [0,35]\'s data')


def main(argv):
    try:
        opts, args = getopt.getopt(argv, "hl")
    except getopt.GetoptError:
        print('error')
        help()
        sys.exit(2)

    if len(opts) == 0:
        print('all')
        allExcel()
    else:

        for opt in opts:
            opt = list(opt)
            opt.remove('')

            if opt[0] == '-l':
                print('start')
                azi = args[0].split(',')[0]
                ele = args[0].split(',')[1]
                screen(azi, ele)  # shaixuan
            elif opt[0] == '-h':
                help()
    print('end')
    exit(0)


if __name__ == '__main__':
    main(sys.argv[1:])
